package com.qinghe.pro.controller.front;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qinghe.pro.Constants;
import com.qinghe.pro.entity.article.Article;
import com.qinghe.pro.entity.main.User;
import com.qinghe.pro.service.article.ArticleService;
import com.qinghe.pro.service.main.UserService;
import com.qinghe.utils.AjaxObject;
import com.qinghe.utils.RegHtml;

@Controller
@RequestMapping("/index")
public class IndexController {
	
	@Autowired
	protected UserService userService;

	@Autowired
	@Qualifier("articleServiceImpl")
	private ArticleService articleService;

	private static final String INDEX = "/index";
	private static final String REGISTERED = "registered";

	/**
	 * 进入首页
	 * 
	 * @param map
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String index(Map<String, Object> map) {
		// 幻灯片
		List<Article> sliderList = articleService.findByType(Constants.COLUMN_TYPE_SLIDER, 5);
		List<String> strList = new ArrayList<String>();
		for (Article at : sliderList) {
			if (StringUtils.isBlank(at.getUrl())) {
				strList = RegHtml.getImgUrl(at.getContent());
				if (strList.size() > 0) {
					at.setUrl(strList.get(0));
				}
			}
		}

		// 右侧新闻栏目
		map.put("articleList", articleService.findByType(Constants.COLUMN_TYPE_RIGHT, 6));
		map.put("sliderList", sliderList);
		
		return INDEX;
	}

	@RequestMapping(method = { RequestMethod.GET }, headers = "X-Requested-With=XMLHttpRequest")
	public @ResponseBody AjaxObject index(HttpServletRequest request) {
		return AjaxObject.newForward(getContextPath(request) + "/index", "登录成功！");
	}

	/**
	 * 进入注册页
	 */
	@RequestMapping(value = "/registered", method = RequestMethod.GET)
	public String preRegistered() {
		return REGISTERED;
	}

	/**
	 * 用户注册
	 * 
	 * @param user
	 */
	@RequestMapping(value = "/registered", method = RequestMethod.POST)
	public @ResponseBody AjaxObject registered(User user) {
		if (StringUtils.isBlank(user.getName())) {
			user.setName(user.getUsername());
		}
		userService.insert(user);

		return AjaxObject.newOk("注册成功，即将跳转至登录页！");
	}

	private static String getContextPath(HttpServletRequest request) {
		return request.getSession().getServletContext().getContextPath();
	}

}
